
Method Overriding
Method overriding happens when a child class defines a method with the same name as a parent class method. When we call that method on the child object, the childโs version gets executed, not the parentโs.
Example of Inheritance
class RailwayForm {
submit() {
console.log("Form submitted at the station counter.");
}
}
class OnlineRailwayForm extends RailwayForm {
// Method Overriding
submit() {
console.log("Form submitted online with digital signature.");
}
}
let offline = new RailwayForm();
offline.submit(); // Output: Form submitted at the station counter.
let online = new OnlineRailwayForm();
online.submit(); // Output: Form submitted online with digital signature.Explanation:-
We use this when we want the child class to customize or change the behavior of an inherited method.
Method Overriding
Example:-
class RailwayForm {
constructor(name, trainNo) {
this.name = name;
this.trainNo = trainNo;
}
submit() {
console.log(`${this.name}'s form submitted for train ${this.trainNo}.`);
}
}
class OnlineRailwayForm extends RailwayForm {
constructor(name, trainNo, email) {
// Call parent constructor first
super(name, trainNo);
this.email = email;
}
submit() {
// Call parent method
super.submit();
// Add extra steps
console.log(`Confirmation email sent to ${this.email}.`);
}
}
let onlineForm = new OnlineRailwayForm("Rohan", 12210, "rohan@example.com");
onlineForm.submit();Explanation:-
This is Constructor Overriding โ customizing the way objects are created.
Difference Between Method and Constructor Overriding
